package com.lagou.dubbo;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class Percentile {

    private Map<String, Map<Long, Long>> elapsedTime = new ConcurrentHashMap<>(3);

    public void add(String key, Long value) {
        Map<Long, Long> values = elapsedTime.computeIfAbsent(key, s -> new TreeMap<>());
        values.put(System.currentTimeMillis(), value);
    }

    @Scheduled(cron = "0/5 * * * * *")
    public void rolling() {
        elapsedTime.keySet().forEach(key -> {
            elapsedTime.compute(key, (key1, oldValue) -> {
                TreeMap<Long, Long> treeMap = (TreeMap<Long, Long>) oldValue;
                SortedMap<Long, Long> newValue = treeMap.subMap(
                        System.currentTimeMillis() - 60, System.currentTimeMillis());
                Collection<Long> values = newValue.values();
                double tp90 = values.size() * 0.9;
                System.out.println("TP90:" + tp90);
                double tp99 = values.size() * 0.99;
                System.out.println("TP99:" + tp90);
                List<Long> collect = values.stream().sorted().collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    Long tp90Value = collect.get((int) Math.ceil(tp90 - 1));
                    System.out.println("TP90Value:" + tp90Value);
                    Long tp99Value = collect.get((int) Math.ceil(tp99 - 1));
                    System.out.println("TP99Value:" + tp99Value);
                }
                return new TreeMap<>(newValue);
            });
        });
    }

}
